package com.zzzzzz.common.util;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageUtils {
	
	public static byte[] scaleImage(byte[] originalBytes, String extension, int boundWidth, int boundHeight) throws IOException {
		BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(originalBytes));
		int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_RGB : originalImage.getType();
		
		int originalWidth = originalImage.getWidth();
		int originalHeight = originalImage.getHeight();
		if (originalWidth <= boundWidth && originalHeight <= boundHeight) {
			return originalBytes;
		}else{
			Dimension scaledDimension = getScaledDimension(originalWidth, originalHeight, boundWidth, boundHeight);
			
			byte[] scaledImage = getScaledImage(originalImage, extension, type, scaledDimension.width, scaledDimension.height);
			return scaledImage;
		}
	}
	
	private static byte[] getScaledImage(BufferedImage originalImage, String extension, int type, int scaledWidth, int scaledHeight) throws IOException {
		BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight , type);
		Graphics2D g = scaledImage.createGraphics();
		g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
		g.dispose();
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		ImageIO.write(scaledImage, extension, byteStream);
		return byteStream.toByteArray();
	}
	
	private static Dimension getScaledDimension(int originalWidth, int originalHeight, int boundWidth, int boundHeight) {
	    int scaledWidth = originalWidth;
	    int scaledHeight = originalHeight;
	    // first check if we need to scale width
	    if (originalWidth > boundWidth) {
	        //scale width to fit
	    	scaledWidth = boundWidth;
	        //scale height to maintain aspect ratio
	    	scaledHeight = (int)(originalHeight * ((float)scaledWidth / (float)originalWidth));
	    }
	    // then check if we need to scale even with the new height
	    if (scaledHeight > boundHeight) {
	        //scale height to fit instead
	    	scaledHeight = boundHeight;
	        //scale width to maintain aspect ratio
	    	scaledWidth = (int)(originalWidth * ((float)scaledHeight / (float)originalHeight));
	    }

	    return new Dimension(scaledWidth, scaledHeight);
	}
	
	public static void main(String[] args){
		System.out.println(getScaledDimension(210, 500, 200, 300));
	}
}
